// 下载界面仓库

import api from '@/api/index'
import { getPMCList } from '@/js/scripts'
import stateCode from '@/js/stateCode';

export default {
    namespaced: true,
    actions: {
        // 通过网址下载文章具体数据
        download_request(context, payload) {

            var pmcList = new Array();

            // 判断是单行下载还是多行下载
            if (payload.PMCID) {
                pmcList.push(payload.PMCID);
            }
            else {
                // 判断当前下载列表是否为空
                if (context.getters.downloadList.length == 0) {
                    alert("下载列表内容为空！");
                    return
                }
                pmcList = getPMCList(context.getters.downloadList);
            }

            // 设置状态为下载中
            context.state.isLoading = true;

            // 改变vue中状态码--正在下载中
            context.commit('UPDATESTATE', { list: pmcList, state: stateCode("正在下载") }, { root: true });

            // 调用API
            api.downloadApi.downloadText(pmcList).then(
                response => {
                    console.log('下载请求成功', response.data);
                    context.state.isLoading = false;

                    // 改变数据库和vue中的状态码
                    api.databaseApi.updateState(pmcList, stateCode("下载成功"));
                    context.commit('UPDATESTATE', { list: pmcList, state: stateCode("下载成功") }, { root: true });

                },
                error => {
                    console.log("下载请求失败", error.message);
                    context.commit('UPDATESTATE', { list: pmcList, state: stateCode("下载失败") }, { root: true });
                    context.state.isLoading = false;
                },
            );
        },
    },
    mutations: {

        // 向下载列表中增加
        AddToList(state, payload) {
            state.textList.push(payload.list);
            console.log(state, payload);
        },

        // 将下载列表中删除
        DeleteInList(state, payload) {
            let index = state.textList.findIndex(i => i.PMCID == payload.PMCID);
            state.textList.splice(index, 1);
        },

        Test(state) {
            console.log(state);
        },
    },
    state: {
        isLoading: false, // 是否处于加载状态
        currentPage: 1, // 当前页数
        pageSize: 50, //每页行数
    },
    getters: {
        // 显示列表
        textList(state, getters, rootState) {
            return rootState.dataList.filter(
                i => i.state == stateCode("准备提取") ||
                    i.state == stateCode("正在下载") ||
                    i.state == stateCode("已下载") ||
                    i.state == stateCode("下载失败")
            );
        },
        // 下载列表
        downloadList(state, getters, rootState) {
            return rootState.dataList.filter(
                i => i.state == stateCode("准备提取")
            );
        },
    },
}